<template>
  <div class="register">
    <h3>注册</h3>
    <el-form :model="userInfo" status-icon :rules="rules" ref="userInfo" label-width="100px" class="demo-userInfo">
      <el-form-item label="账号" prop="username">
        <el-input v-model="userInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="userInfo.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input type="password" v-model="userInfo.checkPassword"></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="userInfo.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('userInfo')">注册</el-button>
        <el-button @click="resetForm('userInfo')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Register',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userInfo.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      userInfo:{
        username:'',
        password:'',
        checkPassword:'',
        name:'',
      },
      rules:{
        username:[
          {required:true,message:'用户名不得为空',trigger:'blur'},
          {min:3,max:32,trigger:'blur'}
        ],
        password:[
          {required:true,message:'密码不得为空',trigger:'blur'},
          {min:3,max:32,trigger:'blur'}
        ],
        checkPassword:[
          {required:true,trigger:'blur',validator: validatePass2},
          {min:3,max:32,trigger:'blur'}
        ],
        name:[
          {required:true,message:'名字不得为空',trigger:'blur'},
          {min:3,max:32,trigger:'blur'}
        ],
      }
    }
  },
  methods:{
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios({
            method:'post',
            data:this.userInfo,
            url:'/api/users/register',
          }).then(res=>{
            console.log(res);
            this.$message.success(res.data.msg)
            this.$router.push('/login')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  components: {
  }
}
</script>

<style lang='less' scoped>
  .register{
    width: 500px;
    margin: 0 auto;
    padding-right: 30px;
    border: 1px solid #dedede;
    border-radius: 5px;
    h3{
      text-align: center;
    }
  }
</style>
